<template>
  <el-select
    v-model="sup_id"
    size="small"
    :remote-method="selSups"
    remote
    filterable
    style="width: 100%"
    placeholder="请选择供应商"
    clearable
    @change="selChange"
    @focus="selSups"
  >
    <el-option
      v-for="item in suppliers"
      :key="item.key"
      :label="item.value"
      :value="item.key"
    />
  </el-select>
</template>

<script>
import { querySupplier, selSups } from '@/api/supplier'

export default {
  name: 'SupplierSelectObject',
  props: {
    value: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      suppliers: [],
      sup_id: null
    }
  },
  watch: {
    'sup_id': {
      handler(n, o) {
        if (this.sup_id && this.sup_id !== '') {
          this.querySupplier()
        }
      },
      immediate: false
    }
  },
  created() {
    this.$set(this, 'sup_id', this.value)
  },
  methods: {
    selChange() {
      this.$emit('input', this.sup_id)
    },
    selSups(query) {
      let str = ''
      if (Object.prototype.toString.call(query) === '[object String]') str = query
      selSups({ name: str }).then(response => {
        this.suppliers = response.list
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    querySupplier() {
      this.$set(this, 'suppliers', [])
      querySupplier({ id: this.sup_id }).then(response => {
        const info = {}
        info.key = response.info.id
        info.value = response.info.name
        this.suppliers.push(info)
      }).catch(err => {
        this.$message.error(err.msg)
      })
    }
  }
}
</script>

<style scoped>
</style>
